<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form" label-width="68px">
      <el-form-item label="登陆名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入登陆名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入电话号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

        <!-- 省市 -->
        <el-form-item label="省市">
            <el-select v-model="queryParams.provinceCode" placeholder="请选择省份" clearable size="small" @change="getCustomCityListFn(2,queryParams.provinceCode)">
                <el-option v-for="item in provinceList" :key="item.id" :label="item.area_name" :value="item.id" />
            </el-select>
            <el-select v-model="queryParams.cityCode" placeholder="请选择市" clearable size="small">
                <el-option v-for="item in cityList" :key="item.id" :label="item.area_name" :value="item.id" />
            </el-select>
        </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="客户类型" prop="status" v-if="isAdmin != 0">
        <el-select v-model="queryParams.highSeasCustomers" placeholder="请选择客户类型" clearable size="small">
          <el-option label="全部" value="0" />
          <el-option label="非公海客户" value="1" />
          <el-option label="公海客户" value="-1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleQt"
          v-hasPermi="['system:customer:qt']"
        >启停</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleChange"
          v-hasPermi="['system:customer:change']"
        >更改业务员</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column min-width="70%" label="登陆名" align="center" prop="userName" />
      <el-table-column min-width="70%" label="真实名" align="center" prop="nickName" />
      <!-- <el-table-column label="身份证号码" align="center" prop="idCard" /> -->
      <!-- <el-table-column label="电子邮件" align="center" prop="email" /> -->
      <el-table-column min-width="70%" label="电话号码" align="center" prop="phonenumber" />
      <el-table-column min-width="25%" label="性别" align="center" prop="sex">
            <template slot-scope="scope">
                {{scope.row.sex === 0 ? '男' : '女'}}
            </template>
      </el-table-column>
      <el-table-column min-width="35%" label="状态" align="center" prop="status">
            <template slot-scope="scope">
                {{scope.row.status === '0' ? '正常' : '停用'}}
            </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="areaCode">
          <template slot-scope="scope">
              {{scope.row.provinceName}} -
              {{scope.row.cityName}}
          </template>
      </el-table-column>

      <el-table-column label="归属业务员" align="center" prop="belongUserName" />
      <el-table-column label="创建人名称" align="center" prop="createName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:customer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['system:customer:edit']"
          >编辑详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:customer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="登陆名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入登陆名" />
        </el-form-item>
        <el-form-item label="真实名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入真实名" />
        </el-form-item>
        <el-form-item label="电子邮件" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮件" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <el-dialog title="更改经理人" :visible.sync="showManager" width="800px" append-to-body>
        <el-form :model="managerParams" :inline="true" class="search-form" label-width="68px">
            <el-form-item label="姓名" prop="userName">
                <el-input
                v-model="managerParams.userName"
                placeholder="请输入姓名"
                clearable
                size="small"
                @keyup.enter.native="managerQuery"
                />
            </el-form-item>
            <el-form-item label="电话号码" prop="phonenumber">
                <el-input
                v-model="managerParams.phonenumber"
                placeholder="请输入姓名"
                clearable
                size="small"
                @keyup.enter.native="managerQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="managerQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="dialogLoading" :data="managerList" @selection-change="manageSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="名称" align="center" prop="userName" />
            <el-table-column label="电话号码" align="center" prop="phonenumber" />
            <el-table-column label="省" align="center" prop="provinceName" />
            <el-table-column label="市" align="center" prop="cityName" />
        </el-table>
      
        <pagination
            v-show="managerTotal>0"
            :total="managerTotal"
            :page.sync="managerParams.pageNum"
            :limit.sync="managerParams.pageSize"
            @pagination="getManagerList"
        />
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="updataManager">确 定</el-button>
            <el-button @click="showManager = false">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, qtCustomer, idCardCustomer, loginNameCustomer, phoneCustomer,getCustomCityList,axios_managerList,axios_updateManager } from "@/api/system/customer";

export default {
  name: "Customer",
  data() {
        var phoneNumber = function(rule, value, callback) {
            if (value && (!(/^[1][34578]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
                callback(new Error('手机号码不符合规范'))
            } else {
                callback()
            }
        }
        
    return {
        managerTotal: 0,
        dialogLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        email: undefined,
        phonenumber: undefined,
        sex: undefined,
        avatar: undefined,
        password: undefined,
        accumulate: undefined,
        shareCode: undefined,
        pShareCode: undefined,
        highSeasCustomers: undefined,
        cId: undefined,
        status: undefined,
        createId: undefined,
        createName: undefined,
        provinceCode: undefined,
        cityCode: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
          userName: [
                { required: true, message: '请输入登录名', trigger: 'blur' }
          ],
          phonenumber: [
                { required: true, message: '请输入手机号码', trigger: 'blur' },
                { validator: phoneNumber, trigger: 'blur' }
          ],
      },
      provinceList: [],
      cityList: [],
      showManager: false,
      checkedManager: '',
      managerList: [],
        managerId: '',
        managerParams: {
            pageNum: 1,
            pageSize: 10,
            nickName: '',
            phonenumber: '',
            userName: '',
            isAdmin: 0,
        }
    };
  },
  created() {
    this.isAdmin = localStorage.getItem('isAdmin');
    this.getList();
    this.getCustomCityListFn(1, null);
  },
  methods: {
      
    // 选择产品
    manageSelectionChange(selection) {
        let managerIds = selection.map(item => item.userId);
        this.managerId = managerIds[0];
        this.dialogSingle = selection.length === 1;
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        // idCard: undefined,
        email: undefined,
        phonenumber: undefined,
        sex: undefined,
        avatar: undefined,
        password: undefined,
        accumulatePoints: undefined,
        shareCode: undefined,
        parentShareCode: undefined,
        isFirstConsume: undefined,
        cId: undefined,
        status: undefined,
        delFlag: undefined,
        createId: undefined,
        createName: undefined,
        createTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.userId || this.ids;
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    // 编辑详情
    handleEdit(row){
        this.$store.dispatch("tagsView/delView", { path: "/customer/edit"});
      	this.$router.push({ path: "/customer/edit", query: { id: row.userId, name: row.nickName}});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      this.$confirm('是否确认选中的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCustomer(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },

    // 启停
    handleQt(row){
        let ids = '';
        if(row.userId){
            ids = row.userId;
        }else{
            ids = this.ids.join(',');
        }

        qtCustomer({ids : ids}).then(response => {
            if (response.code === 200) {
                this.msgSuccess("启停成功");
                this.getList();
            }
        });
    },

        // 获取当前用户的省市
        getCustomCityListFn(type,id){
            getCustomCityList({leveType: type,parentId: id}).then(res => {
                if(res.code === 'success'){
                    if(type === 1){
                        this.provinceList = res.data;
                    }else if(type === 2){
                        this.cityList = res.data;
                        this.queryParams.cityCode = '';
                    }
                }
            });
        },

        // 显示弹框 获取经理人列表
        handleChange(){
            this.managerParams =  {
                pageNum: 1,
                pageSize: 10,
                nickName: '',
                phonenumber: '',
                userName: '',
            };
            this.showManager = true;
            this.getManagerList();
        },


        // 更改经理人列表
        managerQuery(){
            this.managerParams.pageNum = 1;
            this.getManagerList();
        },

        // 更改经理人列表
        getManagerList(){
            this.dialogLoading = true;
            axios_managerList(this.managerParams).then(res => {
                this.dialogLoading = false;
                if (res.code === 200) {
                    this.managerList = res.rows;
                    this.phonenumber = res.total;
                }
            })
        },

        // 更改业务员
        updataManager(){
            let params = {
                userId: this.ids[0],
                managerId: this.managerId
            }
            let that = this;
            axios_updateManager(params).then(res => {
                if (res.code === 'success') {
                    that.showManager = false;
                    this.msgSuccess("更改成功!");
                    this.getList();
                }
            })
        },
  }
};
</script>
<style lang="scss" scoped>
    .search-form{
        .el-input{
            width: 150px;
        }
    }
</style>